package com.esgpro.esg_api.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DruidConfig {
    //绑定yml
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

    //后台监控功能
    @Bean
    public ServletRegistrationBean monitoring() {
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
        HashMap<String, String> hashMap = new HashMap<>();
        //后台需要有人登录，账号密码配置
        //loginUsername\loginPassword前面参数不可乱设置
        hashMap.put("loginUsername", "admin");
        hashMap.put("loginPassword", "123456");
        //允许谁能访问,为空时所有人都能访问
        hashMap.put("allow", "");
        //禁止谁能访问
        // hashMap.put("","");
        //增加配置
        bean.setInitParameters(hashMap);//设置初始化参数(参数需要一个Map)
        return bean;
    }

    //过滤器
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new WebStatFilter());
        //可以过滤哪些请求
        Map<String, String> hashMap = new HashMap<>();
        //这些东西不进行统计
        hashMap.put("exclusions", "*.js,*.css,/druid/*");
        bean.setInitParameters(hashMap);
        return bean;
    }
}
